<template>
  <view>
    <view><text style="font-size: large">提交营销企划书</text> </view>

    <button type="primary" @click="handleUpload">上传文件</button>

    <navigator url="/pages/login" hover-class="navigator-hover">
      <button type="warn">退出</button>
    </navigator>
  </view>
</template>

<script>
import {
  listProposal,
  getProposal,
  addProposal,
  updateProposal,
  delProposal,
} from "@/api/bpm/proposal";
import { getUserProfile, listUser } from "@/api/system/user";

export default {
  data() {
    return {
      user: {},
      // 营销企划书信息表格数据
      proposalList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        marketingProposalName: null,
        marketingProposalFileName: null,
        marketingProposalFileType: null,
        marketingProposalFileExtension: null,
        marketingProposalFilePath: "",
        plannerUserId: null,
        departmentManagerUserId: null,
        auditStatus: null,
        auditResult: null,
        auditFeedback: null,
        submitTime: null,
        auditTime: null,
        executeTime: null,
        executeStatus: null,
      },
      // 查询 市场部部门经理 的 用户查询参数
      queryParamsUser: {
        pageNum: 1,
        pageSize: 10,
        deptId: 104, //市场部门
        postIds: [3], //部门经理
      },
      // 表单，用于新增数据库信息
      form: {},
    };
  },
  onLoad: function () {
    this.getPlanner();

    this.getMarketingDepartmentManager();
  },
  created() {
    this.getList();
  },
  methods: {
    //工具：
    //去除文件扩展名
    removeExtension(filename) {
      const lastDotIndex = filename.lastIndexOf(".");
      if (lastDotIndex === -1) {
        return filename; // 如果没有扩展名，直接返回
      }
      return filename.slice(0, lastDotIndex);
    },

    //截取文件扩展名
    getFileExtension(filename) {
      const parts = filename.split(".");
      if (parts.length === 1) {
        return ""; // 如果没有扩展名，返回空字符串
      }
      return parts[parts.length - 1];
    },

    // 表单重置
    reset() {
      this.form = {
        marketingProposalId: null,
        marketingProposalName: null,
        marketingProposalFileName: null,
        marketingProposalFileType: null,
        marketingProposalFileExtension: null,
        marketingProposalFilePath: "",
        plannerUserId: null,
        departmentManagerUserId: null,
        auditStatus: "",
        auditResult: null,
        auditFeedback: null,
        submitTime: null,
        auditTime: null,
        executeTime: null,
        executeStatus: null,
      };
    },
    /** 查询营销企划书信息列表 */
    getList() {
      listProposal(this.queryParams).then((response) => {
        this.proposalList = response.rows;
        this.total = response.total;
      });
    },

    /** 新增一条数据库记录 */
    async handleAdd() {
      this.form.plannerUserId = this.user.userId;

      try {
        const response = await addProposal(this.form);
        console.log("新增成功", response);
      } catch (error) {
        console.error("新增失败", error);
      }
    },

    //文件上传
    handleUpload() {
      this.reset(); // 每次上传前清空表单

      // 获取市场部部门经理信息
      this.getMarketingDepartmentManager();

      wx.chooseMessageFile({
        count: 1, // 默认1
        type: "file", // 只能选择文件
        success: (res) => {
          console.log("res", res);

          let tempFilePath = res.tempFiles[0].path;
          let tempFileName = res.tempFiles[0].name;
          let tempFileType = res.tempFiles[0].type;

          this.form.marketingProposalFileName = tempFileName;
          this.form.marketingProposalFileType = tempFileType;
          this.form.marketingProposalName = this.removeExtension(tempFileName);
          this.form.marketingProposalFileExtension =
            this.getFileExtension(tempFileName);

          this.form.auditStatus = "未审核";

          this.form.executeStatus = "无";

          this.form.submitTime = new Date().toISOString();

          //上传到服务器
          wx.uploadFile({
            url: "http://localhost:8080/common/upload", // 服务器接口地址
            filePath: tempFilePath,
            name: "file", // 文件对应的 key，服务器通过这个 key 获取文件

            success: (uploadRes) => {
              console.log("上传成功, uploadRes :", uploadRes.data);

              const responseUpload = JSON.parse(uploadRes.data);

              console.log("responseUpload: ", responseUpload);

              this.form.marketingProposalFilePath = responseUpload.url; //文件在数据库的地址

              console.log("上传前: this.form :\n", this.form);

              this.handleAdd(this.form);
            },
            fail: (err) => {
              console.error("上传失败", err);
            },
          });
        },
        fail: (err) => {
          console.error("选择文件失败", err);
        },
      });
    },

    //获取当前登录的用户
    async getCurrentUser() {
      try {
        const response = await getUserProfile();
        this.user = response.data;
      } catch (error) {
        console.error("获取用户信息失败", error);
      }
    },

    //获取策划师信息
    async getPlanner() {
      await this.getCurrentUser();

      this.queryParams.plannerUserId = this.user.userId;

      console.log("planner: ", this.queryParams.plannerUserId);
    },

    //获取市场部部门经理的信息
    getMarketingDepartmentManager() {
      console.log(
        "getMarketingDepartmentManager(), queryParamsUser: ",
        this.queryParamsUser
      );

      listUser(this.queryParamsUser).then((res) => {
        console.log("listUser: ", res.rows[0]);

        this.form.departmentManagerUserId = res.rows[0].userId;
      });
    },
  },
};
</script>

<style lang="scss">
/* #ifndef APP-NVUE */
page {
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  background-color: #fff;
  min-height: 100%;
  height: auto;
}

view {
  font-size: 14px;
  line-height: inherit;
}

/* #endif */

.text {
  text-align: center;
  font-size: 26rpx;
  margin-top: 10rpx;
}

.grsupplier_id-item-box {
  flex: 1;
  /* #ifndef APP-NVUE */
  display: flex;
  /* #endif */
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 15px 0;
}

.uni-margin-wrap {
  wsupplier_idth: 690rpx;
  wsupplier_idth: 100%;
}

.swiper {
  height: 300rpx;
}

.swiper-box {
  height: 150px;
}

.swiper-item {
  /* #ifndef APP-NVUE */
  display: flex;
  /* #endif */
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #fff;
  height: 300rpx;
  line-height: 300rpx;
}

@media screen and (min-wsupplier_idth: 500px) {
  .uni-swiper-dot-box {
    wsupplier_idth: 400px;
    /* #ifndef APP-NVUE */
    margin: 0 auto;
    /* #endif */
    margin-top: 8px;
  }

  .image {
    wsupplier_idth: 100%;
  }
}

.query {
  width: auto;
  margin: 10rpx;
  height: auto;
  /* background-image: linear-gradient(to right, #1f6eb4, #2c9dff); */
}

.th {
  font-weight: bold;
}

.td {
  display: inline-block;
  margin-left: 5rpx;
  width: 100rpx;
}

.td_ {
  display: inline-block;
  margin-left: 5rpx;
  width: 100rpx;
  color: #ff2631;
}

.add {
  position: fixed;
  bottom: 0;
}

.input {
  border: 1px solid lightgray;
  border-radius: 5rpx;
}

.addtitle {
  font-weight: bold;
  text-align: center;
}
</style>
